<template>
  <div class="submergence-control-container">
    <!-- 淹没分析控制面板 -->
    <div class="submergence-control" :class="{ expanded: isPanelExpanded }">
      <!-- 控制图标 -->
      <div class="control-icon" @click="togglePanel" v-if="!isPanelExpanded" title="淹没分析">
        <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M12 3v18M3 12h18M3 6h18M3 18h18"/>
        </svg>
      </div>

      <!-- 淹没分析面板内容 -->
      <div class="submergence-panel" v-if="isPanelExpanded">
        <div class="panel-header">
          <h3>淹没分析</h3>
          <div class="close-btn" @click="isPanelExpanded = false">
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <path d="M18 6L6 18M6 6l12 12"/>
            </svg>
          </div>
        </div>

        <!-- 可滚动内容区域 -->
        <div class="panel-content">
    
    <!-- 区域选择 -->
    <div class="tech-control-row">
      <label>淹没区域</label>
      <div class="tech-button-group">
        <div 
          :class="['tech-btn', { active: currentSubmergenceArea === 'chengdu' }]"
          @click="updateSubmergenceRange('chengdu')"
        >
          成都平原
        </div>
        <div 
          :class="['tech-btn', { active: currentSubmergenceArea === 'beijing' }]"
          @click="updateSubmergenceRange('beijing')"
        >
          北京地区
        </div>
      </div>
    </div>
    
    <!-- 起始高度设置 -->
    <div class="tech-control-row">
      <label>起始高度: {{ startHeight }}m</label>
      <input
        v-model.number="startHeight"
        type="range"
        min="0"
        max="500"
        step="10"
        class="tech-slider"
      >
    </div>
    
    <!-- 目标高度设置 -->
    <div class="tech-control-row">
      <label>目标高度: {{ targetHeight }}m</label>
      <input
        v-model.number="targetHeight"
        type="range"
        min="0"
        max="500"
        step="10"
        class="tech-slider"
      >
    </div>
    
    <!-- 淹没速度设置 -->
    <div class="tech-control-row">
      <label>淹没速度: {{ submergenceSpeed }}m/s</label>
      <input
        v-model.number="submergenceSpeed"
        type="range"
        min="0.1"
        max="5"
        step="0.1"
        class="tech-slider"
      >
    </div>
    
    <!-- 操作按钮 -->
    <div class="tech-button-group">
      <div 
        class="tech-btn" 
        @click="startSubmergenceAnalysis"
        :disabled="isSubmergenceAnalysisRunning"
      >
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <circle cx="12" cy="12" r="10"/>
          <polyline points="12 6 12 12 16 14"/>
        </svg>
        开始
      </div>
      <div 
        class="tech-btn" 
        @click="stopSubmergenceAnalysis"
        :disabled="!isSubmergenceAnalysisRunning"
      >
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <rect x="6" y="4" width="4" height="16"/>
          <rect x="14" y="4" width="4" height="16"/>
        </svg>
        停止
      </div>
      <div 
        class="tech-btn" 
        @click="resetSubmergenceAnalysis"
      >
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
          <path d="M21 2v6h-6M3 12a9 9 0 009 9 9.75 9.75 0 006.74-2.74L21 21M3 21v-6h6M21 12a9 9 0 00-9-9 9.75 9.75 0 00-6.74 2.74L3 3"/>
        </svg>
        重置
      </div>
    </div>
    
        <!-- 状态显示 -->
        <div v-if="submergenceStatus" class="tech-status-message">
          {{ submergenceStatus }}
        </div>
        <div v-if="isSubmergenceAnalysisRunning" class="tech-status-message info">
          当前水位: {{ currentWaterHeight.toFixed(1) }}m
        </div>
      </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import SubmergenceAnalysis from '../utils/SubmergenceAnalysis.js'

// 面板显示状态
const isPanelExpanded = ref(false)

// 组件属性定义
const props = defineProps({
  mapUtils: {
    type: Object,
    required: true
  },
  // 可选的初始区域设置
  initialArea: {
    type: String,
    default: 'chengdu'
  },
  // 可选的初始目标高度
  initialTargetHeight: {
    type: Number,
    default: 100
  },
  // 可选的初始速度
  initialSpeed: {
    type: Number,
    default: 1
  }
})

// 定义事件
const emit = defineEmits([
  'analysis-start',
  'analysis-stop', 
  'analysis-reset',
  'analysis-complete',
  'status-change',
  'area-change'
])

// 淹没分析相关状态
const submergenceAnalysisInstance = ref(null)
const isSubmergenceAnalysisRunning = ref(false)
const targetHeight = ref(props.initialTargetHeight)
const startHeight = ref(0)
const submergenceSpeed = ref(props.initialSpeed)
const currentWaterHeight = ref(0)
const submergenceStatus = ref('')
const currentSubmergenceArea = ref(props.initialArea)

// 核心方法
const createSubmergenceAnalysis = () => {
  try {
    // 检查地图工具是否初始化
    if (!props.mapUtils || !props.mapUtils.viewer) {
      submergenceStatus.value = '地图未初始化，请等待地图加载完成'
      return false
    }
    
    // 如果已有实例，先停止
    if (submergenceAnalysisInstance.value) {
      stopSubmergenceAnalysis()
      submergenceAnalysisInstance.value.clear()
      submergenceAnalysisInstance.value = null
    }
    
    // 获取Cesium实例
    const Cesium = props.mapUtils.customCesium
    
    // 创建新实例
    submergenceAnalysisInstance.value = new SubmergenceAnalysis({
      viewer: props.mapUtils.viewer,
      Cesium: Cesium,
      initialHeight: startHeight.value,
      targetHeight: targetHeight.value,
      speed: submergenceSpeed.value,
      speedCallback: (height) => {
        currentWaterHeight.value = height
      },
      endCallback: () => {
        isSubmergenceAnalysisRunning.value = false
        submergenceStatus.value = '淹没分析完成'
        
        // 发送完成事件
        emit('analysis-complete')
        emit('status-change', '淹没分析完成')
      }
    })
    
    // 默认设置成都平原区域
    updateSubmergenceRange(currentSubmergenceArea.value)
    
    return true
  } catch (error) {
    console.error('创建淹没分析实例失败:', error)
    submergenceStatus.value = '创建淹没分析实例失败'
    return false
  }
}

const startSubmergenceAnalysis = () => {
  try {
    // 如果实例不存在，先创建
    // if (!submergenceAnalysisInstance.value) {
      if (!createSubmergenceAnalysis()) {
        return
      }
    // }
    
    // 检查是否正在运行
    if (isSubmergenceAnalysisRunning.value) {
      submergenceStatus.value = '淹没分析已经在运行中'
      return
    }
    
    // 直接更新实例属性并启动
    const instance = submergenceAnalysisInstance.value
    instance.startHeight = startHeight.value
    instance.targetHeight = targetHeight.value
    instance.speed = submergenceSpeed.value
    instance.waterHeight = startHeight.value // 重置当前水位
    
    instance.start()
    isSubmergenceAnalysisRunning.value = true
    currentWaterHeight.value = startHeight.value
    submergenceStatus.value = '淹没分析开始'
    
    // 发送开始事件
    emit('analysis-start', {
      area: currentSubmergenceArea.value,
      targetHeight: targetHeight.value,
      speed: submergenceSpeed.value
    })
    emit('status-change', '淹没分析开始')
    
    // 定位到淹没区域
    flyToSubmergenceArea()
  } catch (error) {
    console.error('启动淹没分析失败:', error)
    submergenceStatus.value = '启动淹没分析失败'
    isSubmergenceAnalysisRunning.value = false
  }
}

const stopSubmergenceAnalysis = () => {
  try {
    if (submergenceAnalysisInstance.value && isSubmergenceAnalysisRunning.value) {
      submergenceAnalysisInstance.value.stop()
      isSubmergenceAnalysisRunning.value = false
      submergenceStatus.value = '淹没分析已停止'
      
      // 发送停止事件
      emit('analysis-stop')
      emit('status-change', '淹没分析已停止')
    }
  } catch (error) {
    console.error('停止淹没分析失败:', error)
    submergenceStatus.value = '停止淹没分析失败'
  }
}

const resetSubmergenceAnalysis = () => {
  try {
    // 停止当前动画
    stopSubmergenceAnalysis()
    
    // 重置水位
    if (submergenceAnalysisInstance.value) {
      submergenceAnalysisInstance.value.clear()
    }
    
    // 重置状态
    currentWaterHeight.value = startHeight.value
    submergenceStatus.value = '已重置淹没分析'
      
      // 发送重置事件
      emit('analysis-reset')
      emit('status-change', '已重置淹没分析')
  } catch (error) {
    console.error('重置淹没分析失败:', error)
    submergenceStatus.value = '重置淹没分析失败'
  }
}

// 切换面板显示状态
const togglePanel = () => {
  isPanelExpanded.value = !isPanelExpanded.value
}

const updateSubmergenceRange = (area) => {
  try {
    currentSubmergenceArea.value = area
    
    if (submergenceAnalysisInstance.value) {
      let polyCoords
      
      // 根据选择的区域设置多边形坐标
      if (area === 'chengdu') {
        // 成都平原示例坐标
        polyCoords = [
          104.0, 30.5,
        104.1, 30.5,
          104.1, 30.6,
          104.0, 30.6,
          104.0, 30.5]
      } else if (area === 'beijing') {
        // 北京地区示例坐标
        polyCoords = [
          116.3, 39.8,
          116.4, 39.8,
          116.4, 39.9,
          116.3, 39.9,
          116.3, 39.8
        ]
      }
      
      // 更新多边形
      if (polyCoords) {
        submergenceAnalysisInstance.value.updatePoly(polyCoords)
        submergenceStatus.value = `已切换到${area === 'chengdu' ? '成都平原' : '北京地区'}区域`
        
        // 发送区域变更事件
        emit('area-change', area)
        emit('status-change', submergenceStatus.value)
        
        // 如果没有运行分析，更新初始水位显示
        if (!isSubmergenceAnalysisRunning.value) {
          currentWaterHeight.value = startHeight.value
        }
      }
      flyToSubmergenceArea();
    }
  } catch (error) {
    console.error('更新淹没区域失败:', error)
    submergenceStatus.value = '更新淹没区域失败'
  }
}

const flyToSubmergenceArea = () => {
  try {
    if (!props.mapUtils || !props.mapUtils.viewer) return
    
    const Cesium = props.mapUtils.customCesium
    let center
    
    // 根据当前选择的区域设置相机目标位置
    if (currentSubmergenceArea.value === 'chengdu') {
      center = Cesium.Cartesian3.fromDegrees(104.05, 30.55, 2000)
    } else if (currentSubmergenceArea.value === 'beijing') {
      center = Cesium.Cartesian3.fromDegrees(116.35, 39.85, 2000)
    }
    
    if (center) {
      props.mapUtils.viewer.camera.flyTo({
        destination: center,
        duration: 3
      })
    }
  } catch (error) {
    console.error('定位到淹没区域失败:', error)
  }
}

// 组件挂载时初始化
onMounted(() => {
  
})

// 组件卸载时清理资源
onBeforeUnmount(() => {
  try {
    if (submergenceAnalysisInstance.value) {
      stopSubmergenceAnalysis()
      submergenceAnalysisInstance.value.clear()
      submergenceAnalysisInstance.value = null
    }
  } catch (error) {
    console.error('清理淹没分析资源失败:', error)
  }
})
</script>

<style scoped>
.submergence-control-container {
  position: absolute;
  bottom: 100px;
  left: 20px; /* 与标绘组件错开位置 */
  z-index: 10;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 10px;
}

.submergence-control {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 10px;
  transition: all 0.3s ease;
}

.control-icon {
  width: 32px;
  height: 32px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 
    0 8px 32px rgba(102, 126, 234, 0.4),
    0 0 0 1px rgba(255, 255, 255, 0.1);
  transition: all 0.3s ease;
  color: white;
}

.control-icon:hover {
  transform: translateY(-2px);
  box-shadow: 
    0 12px 40px rgba(33, 150, 243, 0.6),
    0 0 0 1px rgba(255, 255, 255, 0.2);
}

.submergence-panel {
  background: linear-gradient(135deg, rgba(15, 23, 42, 0.15) 0%, rgba(30, 41, 59, 0.15) 100%);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.15);
  border-radius: 10px;
  padding: 12px;
  width: 280px;
  max-height: 70vh;
  opacity: 0;
  transform: translateY(20px) scale(0.95);
  pointer-events: none;
  transition: all 0.3s ease;
  box-shadow: 
    0 10px 25px rgba(0, 0, 0, 0.15),
    0 0 0 1px rgba(255, 255, 255, 0.08);
}

/* 可滚动内容区域 */
.panel-content {
  max-height: calc(70vh - 60px); /* 减去头部高度 */
  overflow-y: auto;
  overflow-x: hidden;
}

/* 自定义滚动条样式 */
.panel-content::-webkit-scrollbar {
  width: 6px;
}

.panel-content::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 3px;
}

.panel-content::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 3px;
}

.panel-content::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.3);
}

.submergence-control.expanded .submergence-panel {
  opacity: 1;
  transform: translateY(0) scale(1);
  pointer-events: all;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding-bottom: 10px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.15);
}

.panel-header h3 {
  margin: 0;
  color: white;
  font-size: 16px;
  font-weight: 600;
  letter-spacing: 0.5px;
}

.close-btn {
  width: 28px;
  height: 28px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  color: rgba(255, 255, 255, 0.7);
  transition: all 0.2s ease;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  color: white;
}

/* 淹没分析特有样式 */
.tech-control-row {
  margin-bottom: 16px;
}

.tech-control-row label {
  display: block;
  margin-bottom: 6px;
  color: rgba(255, 255, 255, 0.8);
  font-size: 12px;
  font-weight: 500;
}

.tech-slider {
  width: 100%;
  height: 4px;
  border-radius: 2px;
  background: rgba(255, 255, 255, 0.1);
  outline: none;
  -webkit-appearance: none;
  appearance: none;
}

.tech-slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: linear-gradient(135deg, #2196F3 0%, #03A9F4 100%);
  cursor: pointer;
  box-shadow: 0 2px 6px rgba(33, 150, 243, 0.5);
}

.tech-slider::-moz-range-thumb {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: linear-gradient(135deg, #2196F3 0%, #03A9F4 100%);
  cursor: pointer;
  box-shadow: 0 2px 6px rgba(33, 150, 243, 0.5);
  border: none;
}

.tech-button-group {
  display: flex;
  gap: 8px;
  margin-bottom: 16px;
}

.tech-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  padding: 8px 12px;
  background: rgba(255, 255, 255, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.15);
  border-radius: 6px;
  color: rgba(255, 255, 255, 0.95);
  cursor: pointer;
  transition: all 0.2s ease;
  font-size: 12px;
  font-weight: 500;
}

.tech-btn:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.1);
  border-color: rgba(255, 255, 255, 0.2);
  transform: translateY(-1px);
}

.tech-btn.active {
  background: linear-gradient(135deg, #2196F3 0%, #03A9F4 100%);
  border-color: rgba(255, 255, 255, 0.2);
  color: white;
  box-shadow: 0 4px 15px rgba(33, 150, 243, 0.3);
}

.tech-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.tech-status-message {
  padding: 8px 12px;
  margin-top: 8px;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  border-radius: 6px;
  color: rgba(255, 255, 255, 0.8);
  font-size: 11px;
}

.tech-status-message.info {
  background: rgba(33, 150, 243, 0.1);
  border-color: rgba(33, 150, 243, 0.2);
  color: #BBDEFB;
}
</style>